using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.IRepository;
using SmartLink.Repository.Base;
using Dapper;
using System.Data.Common;
using SmartLink.Domain.ExpandEntity.Base;
using SmartLink.Infrastructure;
using SmartLink.Domain.ExpandEntity;
using SmartLink.Infrastructure.Cache;

namespace SmartLink.Repository
{
    public class PER_RoleGroupRepo : RepositoryBase<PER_RoleGroup>, IPER_RoleGroupRepo
    {
        public bool Exist(string roleName, int oid)
        {
            var sql = "SELECT EXISTS(SELECT * FROM PER_RoleGroup WHERE IsDel=false AND OID=@OID AND RoleName=@RoleName)";
            using (var conn = CreateConn())
            {
                var exist = conn.ExecuteScalar<bool>(sql, new { OID = oid, RoleName = roleName });
                return exist;
            }
        }

        public bool Repeat(int id, string newRoleName, int oid)
        {
            var sql = "SELECT EXISTS(SELECT * FROM PER_RoleGroup WHERE IsDel=false AND OID=@OID AND ID<>@ID AND RoleName=@RoleName)";
            using (var conn = CreateConn())
            {
                var exist = conn.ExecuteScalar<bool>(sql, new { OID = oid, RoleName = newRoleName, ID = id });
                return exist;
            }
        }

        public IEnumerable<PER_RoleGroupExpand> GetRolePaged(bool? enabled, string keyWord, int oid, Pagination pagination)
        {
            var selectSql = "SELECT *, (SELECT COUNT(*) FROM PER_UserToRole WHERE RID=r.ID) MemberCount ";
            var sql = new StringBuilder($@" FROM BIZ_Organization org
                                           JOIN PER_RoleGroup r ON r.OID=org.ID
                                          WHERE r.IsDel=false AND org.ID=@OID
                                            AND r.RoleName<>'{ConstData.SuperManagerRoleName}' AND r.RoleName<>'{ConstData.OrgManagerRoleName}'
                                        ");
            if (enabled.HasValue)
                sql.Append(" AND r.Enabled=@Enabled ");
            if (!string.IsNullOrWhiteSpace(keyWord))
                sql.Append(" AND (r.RoleName LIKE @KeyWord OR r.No LIKE @KeyWord) ");
            var param = new { Enabled = enabled, KeyWord = $"%{keyWord}%", OID = oid };
            using (var conn = CreateConn())
            {
                var list = conn.Query<PER_RoleGroupExpand>(selectSql + sql.ToString() + " ORDER BY r.CreateTime DESC " + pagination.ToLimitString(), param);
                if (pagination.IsSearchTotal)
                    pagination.TotalCount = conn.ExecuteScalar<int>("SELECT COUNT(*) " + sql.ToString(), param);
                return list;
            }
        }

        public int GetRolesCount(int oid)
        {
            var sql = "SELECT COUNT(*) FROM PER_RoleGroup WHERE OID=@OID";
            using (var conn = CreateConn())
            {
                var count = conn.ExecuteScalar<int>(sql, new { OID = oid });
                return count;
            }
        }

        public IList<PER_RoleGroup> GetRoleListByOID(int OID)
        {
            var sql = string.Empty;
            if (CurrentUser.IsSuperAdmin)
                sql = "SELECT * FROM PER_RoleGroup WHERE isDel=0 AND OID=@OID AND Enabled=1 ";
            else if (CurrentUser.IsOrgAdmin)
                sql = $@"SELECT * FROM PER_RoleGroup WHERE isDel=0 AND OID=@OID AND Enabled=1
                                AND !(RoleName='{ConstData.SuperManagerRoleName}' AND IsBuildin=1)";
            else
                sql = $@"SELECT * FROM PER_RoleGroup WHERE isDel=0 AND OID=@OID AND Enabled=1
                                AND !(RoleName='{ConstData.SuperManagerRoleName}' AND IsBuildin=1)
                                AND !(RoleName='{ConstData.OrgManagerRoleName}' AND IsBuildin=1)";
            sql += " ORDER BY ID DESC";
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                return conn.Query<PER_RoleGroup>(sql, new { OID = OID }).AsList();
            }
        }

        public IList<int> GetOrgMangerRoleIds()
        {
            IList<int> results = null;
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format(@"select ID from per_rolegroup where roleName = '公司管理员角色'  and isDel = 0");
                results = conn.Query<int>(sql).AsList();
            }
            return results;
        }


        /// <summary>
        /// 公司id=100下的名称为"公司管理员角色"的角色
        /// </summary>
        /// <returns></returns>
        public PER_RoleGroup GetCompanyManagerRole()
        {
            PER_RoleGroup result = null;
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format(" select * from PER_RoleGroup where isDel=0 and OID=@OID and roleName=@roleName");
                result = conn.QueryFirstOrDefault<PER_RoleGroup>(sql, new { OID = 100, roleName = "公司管理员角色" });
            }
            return result;
        }
        public bool DeleteRoleByOrgId(int orgId)
        {
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                string whereStr = $" where oid = '{orgId}'";
                var sql = string.Format(" delete from per_rolegroup {0} ", whereStr);
                int count = conn.Execute(sql);
                conn.Close();
            }
            return true;
        }

        public void AddDefaultRole(int oid)
        {
            var sql = $@"INSERT INTO PER_RoleGroup (No, OID, RoleName, Enabled, IsBuildin, IsDel, CreateTime, Creator)
                                           VALUES ('{string.Format("{0}{1}", oid, 0.ToString().PadLeft(5, '0'))}',
                                                    {oid}, '{ConstData.OrgManagerRoleName}', 1, 1, 0, '{DateTime.Now}', 0)";
            using (var conn = CreateConn())
            {
                int count = conn.Execute(sql);
            }
        }
    }
}
